// Add a new dynamic form based on an existing dynamic form
function addForm() {
    var total_forms = $('#answer-count').val();

    if (total_forms == 1) {
        $('#delete-0-button').show();
    }

    var new_form = $('#dynamic-form-0').clone();

    updateForm(new_form, total_forms);
    cleanElement(new_form);
    $('.dynamic-formset').append(new_form);

    total_forms++;
    $('#answer-count').val(total_forms);
}

// Delete the give form
function deleteForm(form) {
    var total_forms = $('#answer-count').val();
    var form_number = form.attr('id').match(/\d+/g)[0];

    $('#dynamic-form-' + form_number).remove();

    var index = 0;
    $('.dynamic-formset').find('.dynamic-form').each(function() {
        updateForm($(this), index);
        index++;
    });

    total_forms--;
    $('#answer-count').val(total_forms);

    if (total_forms <= 1) {
        $('#delete-0-button').hide();
    }
}

// Update a form with new index
function updateForm(element, index) {
    $(element).attr('id', $(element).attr('id').replace(/dynamic-form-\d+/, 
                                                    'dynamic-form-' + index));
    $(element).find(':input').each(function() {
        $(this).attr('id', $(this).attr('id').replace(/-\d+-/, 
                                                    '-' + index + '-'));
        $(this).attr('name', $(this).attr('name').replace(/-\d+-/, 
                                                    '-' + index + '-'));
    });
}

// Clean element from old states/data
function cleanElement(element) {
    $(element).find(':input').each(function() {
        if ($(this).attr('type') != 'button') {
            $(this).val('');
        }
        if ($(this).attr('type') == 'checkbox') {
            $(this).prop('checked', false);
        }
    });
}
